package com.proxy.scanandcheck.web.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.proxy.scanandcheck.common.valueobject.ProxyRequest;
import com.proxy.scanandcheck.scaner.controller.ScannerController;
import com.proxy.scanandcheck.scaner.thread.ScannerThreadPool;

 
@Controller
public class ProxyWebController {
 
	private static final Logger LOGGER = Logger.getLogger(ProxyWebController.class);
	
	@Autowired
	private ScannerController scannerController;
	
	@Autowired
	private ScannerThreadPool scannerThreadPool;
	
	@RequestMapping(method = RequestMethod.GET, value = "/start-scan-check")
	public ModelAndView startScanAndCheck() {
 
		
		ProxyRequest proxyRequest = new ProxyRequest();
		proxyRequest.setIpClass(ProxyRequest.A_CLASS);
		proxyRequest.setThreadCount(500);
		proxyRequest.setKeyWords("nba,cnn");
		this.setButtonCss(proxyRequest);
		return new ModelAndView("index", "proxyRequest", proxyRequest);
 
	}
	
	@RequestMapping(method = RequestMethod.POST, value = "/start-scan-check")
	public ModelAndView startScanAndCheck(@ModelAttribute("proxyRequest")ProxyRequest proxyRequest) 
	{
		if(!scannerController.isThreadRunning())
		{
			scannerController.process(proxyRequest);
		}
		else
		{
			LOGGER.info("Thread is running......");
		}
 
		LOGGER.info(proxyRequest);
		this.setButtonCss(proxyRequest);
		return new ModelAndView("index");
 
	}
	
	@RequestMapping(method = RequestMethod.POST, value = "/stop-scan-check")
	public ModelAndView stopScanAndCheck(@ModelAttribute("proxyRequest")ProxyRequest proxyRequest) 
	{
 
		LOGGER.info(proxyRequest);
		scannerThreadPool.shutdowThread();
		this.setButtonCss(proxyRequest);
		return new ModelAndView("index", "proxyRequest", proxyRequest);
 
	}
	
	private void setButtonCss(ProxyRequest proxyRequest)
	{
		if(scannerController.isThreadRunning())
		{
			proxyRequest.setStartButtonCss(ProxyRequest.BUTTON_DISABLED_CSS);
			proxyRequest.setStopButtonCss(ProxyRequest.BUTTON_ENABLED_CSS);
		}
		else
		{
			proxyRequest.setStartButtonCss(ProxyRequest.BUTTON_ENABLED_CSS);
			proxyRequest.setStopButtonCss(ProxyRequest.BUTTON_DISABLED_CSS);
		}
	}
	
}